<template>
  <div class="cart-box"  @click="couponAvailable = -1">
    <!-- LOGO 搜索 -->
    <div class="logo">
      <div>
        <router-link to="/"><img :src="logoImg" /></router-link>
        <div>购物车(<span>{{ goodsTotal }}</span>)</div>
      </div>
    </div>
    <div class="divider mt_10 mb_20"></div>
    <!-- 购物车主体 -->
    <div class="cart-content">
      <div class="available-area">
        <div class="cart-steps">
          <span :class="stepIndex === 0 ? 'active' : ''">1.我的购物车</span>
          <span :class="stepIndex === 1 ? 'active' : ''">2.填写订单信息</span>
          <span :class="stepIndex === 2 ? 'active' : ''">3.成功提交订单</span>
        </div>
      </div>
      <!-- 购物车商品列表 -->
      <div class="cart-goods">
        <div class="cart-goods-title mb_10">
          <div class="" style="width: 60px;">
            <a-checkbox v-model="allChecked" @change="changeChecked(allChecked, 'all')">全选</a-checkbox>
          </div>
          <div class="goods-title" style="width: 600px;">商品</div>
          <div class="" style="width: 150px;">单价（元）</div>
          <div class="" style="width: 100px;">数量</div>
          <div class="" style="width: 150px;">小计</div>
          <div class="" style="width: 100px;">操作</div>
        </div>
        <div v-if="cartList.length === 0" class="cart-empty">
          <p>购物车空空如也</p>
          <router-link to="/" class="link">去选购&gt;</router-link>
        </div>
        <div v-else class="cart-goods-items" v-for="(shop, index) in cartList" :key="index">
          <div class="shop-name">
            <div>
              <a-checkbox v-model="shop.checked" @change="changeChecked(shop.checked, 'shop', shop.storeId)"></a-checkbox>
              <span class="go-shop-page ml_10 hover-pointer hover-color" @click="goShopPage(shop.storeId)">{{shop.storeName}}</span>
            </div>
            <!--优惠券占位-->
            <div>
              <div class="shop-coupon" v-if="shop.couponList.length" :class="couponAvailable === index ? 'shop-coupon-show' : ''" @click.stop="showCoupon(index)">
                <!-- 优惠券模态框 -->
                <div style="z-index: 1000" v-if="couponAvailable === index">
                  <div class="coupon-item" v-for="(item, index) in shop.couponList" :key="index">
                  <span v-if="item.couponType === 'PRICE'">￥{{ item.price }}</span>
                    <span v-if="item.couponType === 'DISCOUNT'">{{ item.couponDiscount }}折</span>
                    <span>满{{ item.consumeThreshold }}元可用</span>
                    <a-button type="primary" status="danger" size="mini" class="mr_10 coupon-btn" @click="receiveShopCoupon(item)" :disabled="item.disabled">{{item.disabled?"已领取":"领取"}}</a-button>
                  </div>
                </div>
              </div>
            </div>
            <div class="promotion-notice fontsize-12">{{ shop.promotionNotice }}</div>
          </div>
          <div v-for="(goods, goodsIndex) in shop.skuList" :key="goodsIndex">
            <div class="goods-item">
              <div style="width: 60px;">
                <a-checkbox v-model="goods.checked" @change="changeChecked(goods.checked, 'goods', goods.goodsSku.id)"></a-checkbox>
              </div>
              <div class="goods-title" style="width: 600px;" @click="goGoodsDetail(goods.goodsSku.id, goods.goodsSku.goodsId)">
                <img :src="goods.goodsSku.thumbnail || '../assets/images/goodsDetail/item-detail-1.jpg'"/>
                <div>
                  <p class="hover-pointer hover-color">{{ goods.goodsSku.goodsName }}</p>
                  <p><a-tag v-if="goods.goodsSku.salesModel === 'WHOLESALE'" class="goods-show-tag" color="purple">批发商品</a-tag></p>
                  <template v-for="(promotion, promotionIndex) in goods.promotions">
                    <div class="promotion" :key="promotionIndex" v-if="promotion.promotionType === 'SECKILL'">
                      <span>秒杀</span>
                      <!--<promotion :time="promotion.endTime" type="cart"></promotion>-->
                    </div>
                  </template>
                  <template v-for="(promotion, promotionIndex) in goods.promotions">
                    <div class="promotion" :key="promotionIndex" v-if="promotion.promotionType === 'FULL_DISCOUNT'">
                      <span>满优惠活动</span>
                      <!--<promotion :time="promotion.endTime" type="cart"></promotion>-->
                    </div>
                  </template>
                </div>
              </div>
              <div class="" style="width: 150px;">{{ unitPrice(goods.purchasePrice, "￥") }}</div>
              <div class="" style="width: 100px;position: relative;">
                <a-input-number v-model="goods.num" :style="{width:'100px'}" :min="1" :max="999" @change="changeNum(goods.num, goods.goodsSku.id)"></a-input-number>
                <div class="fontsize-12" style="position: absolute;top: 58px;">{{ goods.goodsSku.quantity > 0 ? "有货" : "无货" }}</div>
              </div>
              <div class="" style="width: 150px;">{{ unitPrice(goods.subTotal, "￥") }}
              </div>
              <div class="" style="z-index: 100;width: 100px;">
                <a-button type="primary" status="danger" size="mini" class="mr_10" @click="handleDelGoods(goods.goodsSku.id)">删除</a-button>
                <a-button type="primary" status="warning" size="mini" v-if="!goods.errorMessage" @click="handleCollectGoods(goods.goodsSku.id)">收藏</a-button>
              </div>
              <div :class="(goods.errorMessage && goods.errorMessage.indexOf('不足') > -1) ? 'error-goods-no-enough' : 'error-goods' " v-if="goods.errorMessage">
                <div style="margin-top: 54px;margin-left: 160px;">{{ goods.errorMessage }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部支付栏 -->
        <div class="cart-goods-footer mt_10 mb_10">
          <div>
            <div class="width_60">
              <a-checkbox v-model="allChecked" @change="changeChecked(allChecked, 'all')">全选</a-checkbox>
            </div>
            <div class="handle-btn" @click="handleDelGoods()">删除选中商品</div>
            <div class="handle-btn" @click="handleClearCart">清空购物车</div>
          </div>
          <div>
            <div class="selected-count">已选择<span>{{ checkedNum }}</span>件商品</div>
            <div class="ml_20 save-price">已节省<span>{{ unitPrice(priceDetailDTO.discountPrice, "￥")}}</span></div>
            <div class="ml_20 total-price">总价（不含运费）:<div>{{ unitPrice(priceDetailDTO.flowPrice, "￥") }}</div></div>
            <div class="ml_20 pay" @click="pay">去结算</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import { unitPrice } from '@/utils/filters';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/stores/user';
  import { storeToRefs } from 'pinia';
  import { delCartGoods, clearCart, setCartGoodsNum, setCheckedAll, setCheckedSeller, setCheckedGoods, cartGoodsAll, cartCount } from "@/api/cart";
  import { collectGoods, receiveCoupon, couponList } from "@/api/member";

  const router = useRouter();
  // 状态管理
  const store = useUserStore();
  const { logoImg } = storeToRefs(store);
  const loading = ref<boolean>(false); // 加载状态
  const couponAvailable = ref<number>(-1); // 展示优惠券
  const stepIndex = ref<number>(0); // 当前处于哪一步，购物车==0，填写订单信息==1，成功提交订单==2
  const goodsTotal = ref<number>(0); // 商品数量
  const checkedNum = ref<number>(0); // 选中数量
  const allChecked = ref<boolean>(false); // 全选
  const cartList = ref<any>([]); // 购物车列表
  const priceDetailDTO = ref<any>({}); // 价格明细
  const skuList = ref<Array<any>>([]); // sku列表

  // 跳转商品详情
  const goGoodsDetail = (skuId: any, goodsId: any) => {
    let routeUrl = router.resolve({path: "/goodsDetail", query: { skuId, goodsId },});
    window.open(routeUrl.href, "_blank");
  };
  // 跳转店铺首页
  const goShopPage = (id: any) => {
    let routeUrl = router.resolve({path: "/merchant", query: { id },});
    window.open(routeUrl.href, "_blank");
  };
  // 收藏商品
  const handleCollectGoods = (id: any) => {
    Modal.confirm({
      title: '收藏',
      content: `商品收藏后可在个人中心我的收藏查看`,
      okButtonProps: {type: "primary", status: "danger"},
      onOk: () => {
        collectGoods("GOODS", id).then((res: any) => {
          if (res.data.success) {
            Message.success("收藏商品成功");
            getCartList();
          }
        });
      }
    });
  };
  // 删除商品
  const handleDelGoods = (id?: any) => {
    const idArr = [] as any;
    if (!id) {
      const list = cartList.value;
      list.forEach((shop: any) => {
        shop.skuList.forEach((goods: any) => {
          if (goods.checked) {idArr.push(goods.goodsSku.id);}
        });
      });
    } else {
      idArr.push(id);
    }
    Modal.confirm({
      title: '删除',
      content: `确定要删除该商品吗`,
      okButtonProps: {type: "primary", status: "danger"},
      onOk: () => {
        delCartGoods({ skuIds: idArr.toString() }).then((res: any) => {
          if (res.data.success) {
            Message.success("删除成功");
            getCartList();
          } else {
            Message.error(res.data.message);
          }
        });
      }
    });
  };
  // 清空购物车
  const handleClearCart = () => {
    Modal.confirm({
      title: '提示',
      content: `确定要清空购物车吗？清空后不可恢复`,
      okButtonProps: {type: "primary", status: "danger"},
      onOk: () => {
        clearCart().then((res: any) => {
          if (res.data.success) {
            Message.success("清空购物车成功");
            getCartList();
          } else {
            Message.error(res.data.message);
          }
        });
      }
    });
  };
  // 跳转支付页面
  const pay = () => {
    if (checkedNum.value) {
      router.push({ path: "/payment/pay", query: { way: "CART" } });
    } else {
      Message.warning("请至少选择一件商品");
    }
  };


  // 设置购买数量
  const changeNum =(val: number | string, id: number | string) => {
    if (val) {
      setCartGoodsNum({ skuId: id, num: val }).then((res: any) => {
        if (res.data.success) {
          getCartList();
        }
      });
    }
  };
  // 设置商品选中状态
  const changeChecked = async (status: any, type: any, id?: any) => {
    const check = status ? 1 : 0;
    if (type === "all") {
      // 全选
      await setCheckedAll({ checked: check });
    } else if (type === "shop") {
      // 选中店铺所有商品
      await setCheckedSeller({ checked: check, storeId: id });
    } else {
      // 单个商品
      await setCheckedGoods({ checked: check, skuId: id });
    }
    getCartList();
  };
  // 展示优惠券
  const showCoupon = (index: number) => {
    couponAvailable.value = index;
  };
  // 领取优惠券
  const receiveShopCoupon = async (item: any) => {
    let res = await receiveCoupon(item.id);
    if (res.data.success) {
      item.disabled = true;
      Message.success("领取成功");
    } else {
      Message.error(res.data.message);
    }
  };




  // 购物车列表
  const getCartList = async () => {
    loading.value = true;
    try {
      let res = await cartGoodsAll();
      loading.value = false;
      if (res.data.success) {
        cartList.value = res.data.result.cartList;
        priceDetailDTO.value = res.data.result.priceDetailDTO;
        skuList.value = res.data.result.skuList;
        checkedNum.value = 0;
        let allCheckeds = true;
        for (const element of cartList.value) {
          let shop = element as any;
          let list = await couponList({ storeId: shop.storeId, getType: 'FREE' });
          shop.couponList.push(...list.data.result.records);
        }
        for (const element of skuList.value) {
          if (element.checked) {
            checkedNum.value += element.num;
          } else {
            allCheckeds = false;
          }
        }
        allChecked.value = allCheckeds;
      }
    } catch (error) {
      loading.value = false;
    }
  };

  onMounted(() => {
    getCartList();
    cartCount().then((res: any) => {
      // 购物车商品数量
      if (res.data.success) goodsTotal.value = res.data.result;
    });
  })
</script>

<style scoped lang="less">
  .cart-box {
    background-color: @light_background_color;
    overflow: hidden;
  }
  .logo {
    width: 1200px;
    height: 90px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin: 0 auto;
    div:nth-child(1) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      img {
        max-height: 80px;
        height: auto;
        cursor: pointer;
      }
      div:nth-child(2) {
        width: 200px;
        color: #999;
        font-size: 16px;
        margin: 0 20px;
        span {
          color: @theme_color;
        }
      }
    }
  }
  .divider {
    width: 100%;
    height: 2px;
    background-color: @theme_color;
  }
  /*购物车主体*/
  .cart-content {
    color: #666666;
    margin: 0 auto;
    width: 1200px;
    position: relative;
    /** 步骤条和配送区域总体 */
    .available-area {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
    }
    /** step步骤条 */
    .cart-steps {
      height: 30px;
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      span {
        color: @light_content_color;
        height: 30px;
        text-align: center;
        line-height: 30px;
        display: inline-block;
        padding: 0 15px;
      }
      .ivu-icon {
        color: @light_content_color;
        font-size: 20px;
        margin: 0 15px;
      }
      .active {
        border-radius: 50px;
        background-color: #ff8f23;
        color: #fff;
      }
      .active-arrow {
        color: #ff8f23;
      }
    }
  }
  /** 商品列表 */
  .cart-goods {
    .cart-goods-title {
      display: flex;
      background-color: #ffffff;
      padding: 10px 0;
      color: #666666;
      text-align: center;
    }
    .cart-goods-items {
      .shop-name {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin: 15px 0 10px;
        > div:nth-of-type(1) {
          display: flex;
          align-items: center;
        }
        .shop-coupon {
          width: 80px;
          height: 24px;
          position: relative;
          background: url(../assets/images/cart-coupon-icons02.png) 0 0 no-repeat;
          > div {
            position: absolute;
            top: 35px;
            left: 0;
            width: 300px;
            background-color: #fff;
            border: 1px solid @theme_color;
            border-radius: 3px;
            z-index: 1;
            padding: 14px 20px 4px;
            &::before {
              content: "";
              display: block;
              background: url(../assets/images/cart-coupon-icons02.png) 0 -58px no-repeat;
              width: 80px;
              height: 12px;
              position: absolute;
              top: -12px;
              left: 0;
            }
            .coupon-item {
              margin-bottom: 10px;
              span:nth-child(1) {
                border: 1px solid #e33937;
                display: inline-block;
                padding: 3px 10px;
                color: @theme_color;
                border-radius: 3px;
              }
              span:nth-child(2) {
                font-size: 12px;
                margin-left: 5px;
                color: #999;
              }
              .coupon-btn {
                height: 26px;
                float: right;
                font-size: 12px;
              }
              &::after {
                display: block;
                content: "";
                clear: right;
              }
            }
          }
        }
      }
      .goods-item {
        display: flex;
        background-color: #ffffff;
        padding: 10px 0;
        border-bottom: 1px solid #efefef;
        position: relative;
        > div {
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .goods-title {
          cursor: pointer;
          display: flex;
          box-sizing: border-box;
          padding-left: 20px;
          position: relative;
          justify-content: flex-start;
          img {
            width: 70px;
            height: 70px;
            margin-right: 10px;
          }
        }
        .error-goods-no-enough {
          position: absolute;
          top: 0;
          left: 0;
          box-sizing: border-box;
          height: 100%;
          z-index: 10;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #000;
        }
        .error-goods {
          position: absolute;
          top: 0;
          left: 0;
          box-sizing: border-box;
          width: 100%;
          height: 100%;
          background-color: rgba(200, 200, 200, 0.4);
          z-index: 10;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #000;
        }
      }
    }



    .cart-empty {
      width: 100%;
      text-align: center;
      height: 300px;
      padding-top: 100px;
      .link {
        text-decoration: none;
        color: @link_color;
      }
    }
  }
  /*底部支付栏*/
  .cart-goods-footer {
    position: sticky;
    bottom: 0;
    border-top: 1px solid #ddd;
    padding: 0 0 0 20px;
    line-height: 50px;
    justify-content: space-between;
    height: 50px;
    background-color: #fff;
    transition: 0.35s;
    color: #8c8c8c;
    display: flex;
    align-items: center;
    z-index: 101;
    > div {
      display: flex;
      align-items: center;
      overflow: hidden;
    }
    .selected-count {
      span {
        color: @theme_color;
      }
    }

    .save-price span {
      color: #000;
    }
    .total-price div {
      color: @theme_color;
      font-size: 20px;
    }
    .pay {
      background-color: @theme_color;
      width: 150px;
      font-size: 20px;
      color: #fff;
      height: 100%;
      line-height: 50px;
      cursor: pointer;
      text-align: center;
    }
    .handle-btn {
      width: 100px;
      text-align: center;
      font-size: 12px;
      color: #438cde;
      cursor: pointer;
      &:hover {
        color: @theme_color;
      }
    }
  }
  .total-price {
    display: flex;
    align-items: center;
  }
</style>
